package test.controller;

import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import test.util.CustomizedPropertyPlaceholderConfigurer;
import test.util.FileUploadUtil;

@Controller
@RequestMapping("/file")
public class FileUploadController {
	
	//自动加载配置文件中的配置
	//@Value("${path.dir}")  如果使用注解，spring会自动注入，如果没有配置，就会报错
	private String path= "";  
	
	//获取日志log
	private Logger log= Logger.getLogger(this.getClass());
	
	@RequestMapping(method=RequestMethod.GET)
	public String test(){
		return "index";
	}
	
	@RequestMapping(value = "/saveImage", method = RequestMethod.POST ,produces="text/plain;charset=UTF-8")
	@ResponseBody
	public String saveImgFile(HttpServletRequest request){
		JSONObject res= new JSONObject();  //返回结果
		if(CustomizedPropertyPlaceholderConfigurer.containKey("path.dir")){
			path= CustomizedPropertyPlaceholderConfigurer.getContextProperty("path.dir").toString();
		}
		
		try{
			JSONObject obj = FileUploadUtil.readJSONByFileItemStream(request);
			String imgStr= obj.getString("image");  //从前台传递过来的是 image属性保存的图片base64的字符串
			String name= obj.containsKey("Filename")?obj.getString("Filename"):"";  //如果含有name属性
			
			if(this.path!= null && !"".equals(this.path)){
				name= FileUploadUtil.saveFile(imgStr, this.path, name);
				log.info("保存文件成功，路径："+ this.path+File.separator+",文件名称："+name);
			}else{
				//如果没有配置该参数，使用默认上传到该项目根目录下面的upload目录下面
				String path= request.getSession().getServletContext().getRealPath("")+File.separator+"upload";
				name= FileUploadUtil.saveFile(imgStr, path, name);
				log.info("保存文件成功，路径："+ path+File.separator+",文件名称："+name);
			}
			res.put("status", 1);
			res.put("msg", "上传成功");
		}catch(Exception ex){
			ex.printStackTrace();
			res.put("status", 0);
			res.put("msg", "上传失败");
		}
		
		return res.toString();
	}
	
	
	@RequestMapping(value="/getImage", method=RequestMethod.GET)
	public void getImage(HttpServletRequest request, HttpServletResponse response)throws Exception{
		String file = "G:/" + "67.png";  //图片在项目的根目录下面
		BufferedImage image = ImageIO.read(new File(file));
		ImageIO.write(image, "png", response.getOutputStream());
		System.out.println("getImage");
	}
}
